<?php
declare (strict_types = 1);

namespace app\home\controller;

use app\BaseController;
use app\common\model\User\Collection as CollectionModel;
use app\home\middleware\Auth;
use think\exception\ValidateException;
use app\common\validate\User\Collection as CollectionValidate;
use think\facade\View;

class Collection extends BaseController
{
    // 控制器中间件
    protected $middleware = [
        Auth::class
    ];

    public function index()
    {
        $title = '我的收藏';

        $collectionList = CollectionModel::withJoin(['user','post'])->where(['collection.userid' => $this->request->LoginUser['id']])->order('collection.createtime','desc')->paginate(['list_rows' => 10,'query' => request()->param()]);

        $total = $collectionList->total();

        return View::fetch('',[
            'title' => $title,
            'collectionList' => $collectionList,
            'total' => $total,
        ]);
    }


    // 添加收藏
    public function add()
    {
        if($this->request->isAjax())
        {
            $postid = $this->request->param('postid',0);

            $userid = $this->request->LoginUser['id'] ? $this->request->LoginUser['id'] : 0;

            $collect = CollectionModel::where(['postid' => $postid,'userid' => $userid])->find();

            if($collect)
            {
                // 能进入这里说明该用户已经收藏该帖子，这里写取消收藏的逻辑
                $collection = CollectionModel::find($collect['id']);

                $result = $collection->delete();

                if($result !== true)
                {
                    $this->error('取消收藏失败');
                }else{
                    $this->success('取消收藏成功');
                }

            }else{
                // 能进入这里说明该用户未收藏该帖子，这里写收藏的逻辑
                $data = [
                    'userid' => $userid,
                    'postid' => $postid
                ];

                try {
                    validate(CollectionValidate::class)->check($data);
                } catch (ValidateException $e) {
                   $this->error($e->getError());
                }

                $collection = new CollectionModel();

                $result = $collection->save($data);

                if($result !== true)
                {
                    $this->error('收藏失败');
                }else{
                    $this->success('收藏成功');
                }
            }
        }
    }
}
